package com.zhaochao.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ParameterMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;;

public class MySQL {
	private Connection conn;
	private PreparedStatement ps;
	private ResultSet rs;
	private ResultSetMetaData rsData;

	public MySQL(iConn icon) throws Exception {
		try {
			this.conn = icon.getConn();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw e;
		}
	}

	// 获取表
	public Table ExecuteSQL(String sql, String[] paramters) throws SQLException {
		this.ps = this.conn.prepareStatement(sql);
		if (paramters != null) {
			for (int i = 1; i <= paramters.length; i++) {
				this.ps.setString(i, paramters[i - 1]);
			}
		}
		this.rs = this.ps.executeQuery();
		TableHead tableHead = null;
		Table table = null;
		this.rsData = this.rs.getMetaData();
		int columnCount = this.rsData.getColumnCount();
		table = new Table(columnCount);
		tableHead = new TableHead(columnCount);
		tableHead.setTableName(this.rsData.getTableName(1));
		for (int i = 1; i <= this.rsData.getColumnCount(); i++) {
			tableHead.setTableColumnName(this.rsData.getColumnName(i), i);
		}
		// 设置表头
		table.setTablehead(tableHead);

		while (this.rs.next()) {
			TableContent content = new TableContent(columnCount);
			for (int i = 1; i <= columnCount; i++) {
				content.setTableContent(this.rs.getString(i), i);
			}
			// 加入字段
			table.addContent(content);
		}
		return table;
	}

	private void close() {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		if (ps != null) {
			try {
				ps.close();
			} catch (SQLException e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	}

}
